package com.yalemang.framework.utils

import android.app.Activity
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle

/**
 * App前后台切换监听
 */
abstract class AppSwitchListener : ActivityLifecycleCallbacks {

    private var activityList : ArrayList<Activity> = ArrayList()
    private var activeActivityQuantity : Int = -1

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        activityList.add(activity)
    }

    override fun onActivityStarted(activity: Activity) {

    }

    override fun onActivityResumed(activity: Activity) {
        if (activeActivityQuantity == 0){
           switch(false, activity)
        }else if (activeActivityQuantity == -1){
            activeActivityQuantity = 0
        }

        activeActivityQuantity++
    }

    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStopped(activity: Activity) {
        activeActivityQuantity--
        if (activeActivityQuantity == 0) {
            switch(true, activity)
        }
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {
        activityList.remove(activity)
    }

    abstract fun switch(isBackstage: Boolean, activity: Activity)
}